 package com.gxuwz.security;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.gxuwz.business.entity.SysUser;
import com.gxuwz.business.service.ISysRoleRightService;
import com.gxuwz.business.service.ISysUserService;

/**
 * 获取登录用户拥有的权限id
 * @author Administrator
 *
 */

@Service("userDetailService")
public class UserDetailServiceImpl implements UserDetailsService {
	
	@Autowired
	private ISysUserService userService;
	@Autowired
	private ISysRoleRightService sysRoleRightService;
	
	private final Logger log = Logger.getLogger(getClass());

	@Override
	public UserDetails loadUserByUsername(String userId)
			throws UsernameNotFoundException {
		List<GrantedAuthority> auth = new ArrayList<GrantedAuthority>();
		SysUser user = userService.findByName(userId);
		//查找用户名对应的权限id集合
//		log.info("传来的userId: "+userId);
		List<String> rightIds = sysRoleRightService.findByUserId(user.getUserId());
		
		for (String rightId : rightIds) {
			auth.add(new SimpleGrantedAuthority(rightId));
		}
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		log.info("用户拥有的权限："+auth);
		User userdetails = new User(user.getUserName(), user.getUserPassword(),enabled, accountNonExpired, credentialsNonExpired,	accountNonLocked, auth);
		return userdetails;
	}

	public ISysUserService getUserService() {
		return userService;
	}

	public void setUserService(ISysUserService userService) {
		this.userService = userService;
	}

}
